package org.ykh.service.policy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.ykh.common.utils.HttpUtils;
import org.ykh.service.policy.RestrictPolicy;


import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.temporal.ChronoUnit;

/**
 * @author ykh
 */
@Component
public class ShieldRestrictPolicy implements RestrictPolicy {


    @Autowired
    private StringRedisTemplate redisTemplate;

    //一旦在单位时间超过频率进入ipset永远被屏蔽。
    @Override
    public boolean isRestrict(HttpServletRequest request, String encoded,Duration interval,int threshold) {
        final SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
        final String ip = HttpUtils.ip(request);
        final Boolean isShield = opsForSet.isMember("ipset", ip);
        return isShield != null && isShield;
    }


    @Override
    public void restrictPolicy(HttpServletRequest request, String encoded, Duration interval,int threshold) {

        final SetOperations<String, String> opsForSet = redisTemplate.opsForSet();

        String ip = HttpUtils.ip(request);
        String key = ip + ":" + encoded;

        final ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

        final Boolean aBoolean = opsForValue.setIfAbsent(key, "1",interval);

        if (aBoolean != null && !aBoolean) {
            final Long increment = opsForValue.increment(key);
            //加入屏蔽列表
            if (increment != null && increment > threshold) {
                opsForSet.add("ipset", ip);
            }
        }
    }

}
